package com.cold.legendary.mock.proxy;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.cglib.proxy.Enhancer;

/**
 * @author cold
 * @since  2022/1/19
 */
@Slf4j
public class LMockFactoryBean<T> implements FactoryBean<T> {

    private String mockBeanName;
    private Class<?> mockBeanClass;
    private Object mockInjectObject;
    private Object mockBean;

    public LMockFactoryBean(String mockBeanName, Class<?> mockBeanClass, Object mockInjectObject, Object mockBean) {
        this.mockBeanName = mockBeanName;
        this.mockBeanClass = mockBeanClass;
        this.mockInjectObject = mockInjectObject;
        this.mockBean = mockBean;
    }

    @Override
    public T getObject()  {
        log.info("正在为{}生成代理对象", mockBeanName);

        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(mockBeanClass);
        //设置方法拦截处理器
        enhancer.setCallback(new LMockMethodInterceptor(mockBeanName, mockInjectObject, mockBean));
        //创建代理对象
        Object proxyMockBean = enhancer.create();
        T t = (T)proxyMockBean;
        return t;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }

    @Override
    public Class<?> getObjectType() {
        return mockBeanClass;
    }
}
